<template>
  <list-card>
    <template v-slot:search>
      <el-form v-show="showSearch" ref="queryForm" inline :model="queryParams" label-suffix="：" size="small">
        <el-form-item label="任务名称" prop="jobName">
          <el-input v-model="queryParams.jobName" clearable placeholder="请输入任务名称"
                    @keyup.enter.native="handleQuery"/>
        </el-form-item>
        <el-form-item label="任务组名" prop="jobGroup">
          <el-select v-model="queryParams.jobGroup" clearable placeholder="请选择任务组名">
            <el-option v-for="item in localDict.quartz_group" :key="item.value" :label="item.label"
                       :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="任务状态" prop="status">
          <el-select v-model="queryParams.status" clearable placeholder="请选择任务状态">
            <el-option v-for="item in localDict.quartz_status" :key="item.value" :label="item.label"
                       :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-search" size="mini" type="primary" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" type="info" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </template>
    <template v-slot:operate>
      <el-button icon="el-icon-plus" size="mini" type="primary" @click="handleAdd">新增</el-button>
      <el-button :disabled="multiple" icon="el-icon-delete" size="mini" @click="handleDelete">删除</el-button>
      <!--      <el-button icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"/>
    </template>
    <template v-slot:content>
      <el-table v-loading="loading" :data="dataList" @selection-change="handleSelectionChange">
        <el-table-column align="center" type="selection" width="40px"/>
        <el-table-column label="任务名称" min-width="150px" prop="jobName" show-overflow-tooltip/>
        <el-table-column label="任务组名" min-width="100px" prop="jobGroup">
          <template v-slot:default="scope">
            <dict-tag :options="localDict.quartz_group" :value="scope.row.jobGroup" show-label/>
          </template>
        </el-table-column>
        <el-table-column label="调用目标字符串" min-width="160px" prop="invokeTarget" show-overflow-tooltip/>
        <el-table-column label="cron执行表达式" min-width="150px" prop="cronExpression"/>
        <el-table-column label="状态" min-width="100px">
          <template v-slot:default="scope">
            <el-switch v-model="scope.row.status" active-value="00" inactive-value="01"
                       @change="handleStatusChange(scope.row)"/>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" min-width="160px">
          <template v-slot:default="scope">
            <el-button icon="el-icon-view" type="text" @click="handleView(scope.row)">任务详细</el-button>
            <el-divider direction="vertical"/>
            <el-dropdown size="mini" split-button type="text" @command="handleCommand">更多
              <template v-slot:dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item :command="{ row: scope.row, command: 'edit', title: '修改任务信息' }"
                                    icon="el-icon-edit">修改
                  </el-dropdown-item>
                  <el-dropdown-item :command="{ row: scope.row, command: 'delete', title: '删除任务信息' }"
                                    icon="el-icon-delete">删除
                  </el-dropdown-item>
                  <el-dropdown-item :command="{ row: scope.row, command: 'run', title: '执行任务' }"
                                    icon="el-icon-caret-right">执行一次
                  </el-dropdown-item>
                  <el-dropdown-item :command="{ row: scope.row, command: 'log', title: '调度日志' }"
                                    icon="el-icon-s-operation">调度日志
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="pageParam.total>0" :limit.sync="pageParam.pageSize" :page.sync="pageParam.pageNum"
                  :total="pageParam.total" @pagination="getList"/>
    </template>
    <model-card ref="model" @ok="getList"/>
  </list-card>
</template>

<script>
import moment from "moment/moment";
import Crontab from '@/components/Crontab'
import {list, remove, save} from "@/api/base";
import {getStaticData} from "@/api/common";
import ModelCard from "./components/ModelCard.vue";

export default {
  components: {ModelCard, Crontab},
  name: "Quartz",
  dicts: [],
  data() {
    return {
      // 选中数组
      ids: [],
      // 遮罩层
      loading: true,
      baseUrl: '/monitor/job/',
      commonUrl: '/api/quartz/static/',
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: false,
      dataList: [],
      // 查询参数
      queryParams: {
        jobName: undefined,
        jobGroup: undefined,
        status: undefined
      },
      pageParam: {
        // 总条数
        total: 0,
        pageNum: 1,
        pageSize: 10,
      },
      dialog: {
        open: false,
        cron: false,
        title: "",
      },
      view: {
        // 是否显示详细弹出层
        open: false,
      },
      cron: {
        open: false,
        expression: "",
      },
      localDict: {
        quartz_group: [],
        quartz_status: [],
        quartz_strategy: []
      },
      // 表单参数
      formdata: {},
      // 表单校验
      rules: {
        jobName: [
          {required: true, message: "任务名称不能为空", trigger: "blur"}
        ],
        invokeTarget: [
          {required: true, message: "调用目标字符串不能为空", trigger: "blur"}
        ],
        cronExpression: [
          {required: true, message: "cron执行表达式不能为空", trigger: "blur"}
        ]
      }
    };
  },
  created() {
    this.getLocalDict()
    this.resetQuery();
  },
  methods: {
    getLocalDict() {
      this.getStaticData('system-quartz-group').then(res => {
        this.localDict.quartz_group = res.data
      })
      this.getStaticData('system-quartz-status').then(res => {
        this.localDict.quartz_status = res.data
      })
      this.getStaticData('system-quartz-strategy').then(res => {
        this.localDict.quartz_strategy = res.data
      })
    },
    /** 查询定时任务列表 */
    getList() {
      this.loading = true;
      list(this.baseUrl, {
        ...this.queryParams,
        pageNum: this.pageParam.pageNum,
        pageSize: this.pageParam.pageSize
      }).then(response => {
        this.dataList = response.rows;
        this.pageParam.total = response.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.pageParam.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    // 更多操作触发
    handleCommand(command) {
      switch (command.command) {
        case "edit":
          this.handleUpdate(command.row);
          break;
        case "delete":
          this.handleDelete(command.row);
          break;
        case "run":
          this.handleRun(command.row);
          break;
        case "view":
          this.handleView(command.row);
          break;
        case "log":
          this.handleJobLog(command.row);
          break;
        default:
          break;
      }
    },
    // 任务状态修改
    handleStatusChange(row) {
      let text = row.status === "00" ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '""' + row.jobName + '"任务吗？').then(function () {
        return changeJobStatus(row.id, row.status);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function () {
        row.status = row.status === "00" ? "01" : "00";
      });
    },
    /* 立即执行一次 */
    handleRun(row) {
      this.$modal.confirm('确认要立即执行一次"' + row.jobName + '"任务吗？').then(function () {
        return runJob(row.id, row.jobGroup);
      }).then(() => {
        this.$modal.msgSuccess("执行成功");
      }).catch(() => {
      });
    },
    /** 任务详细信息 */
    handleView(row) {
      this.$router.push({name: 'JobDetail', path: '/developer/job-log/detail/' + row.id, params: {id: row.id}})
    },

    /** 任务日志列表查询 */
    handleJobLog(row) {
      const id = row.id || 0;
      this.$router.push({path: '/developer/job-log/index', query: {id: id, name: row.jobName, group: row.jobGroup}})
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$refs.model.handleAdd()
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.$refs.model.handleEdit(row.id)
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除选择的定时任务？').then(() => {
        remove(this.baseUrl, ids).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {
        })
      });
    },
    /** 提交按钮 */
    handleSubmit: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          save(this.baseUrl, this.formdata).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.dialog.open = false;
            this.handleReset()
            this.getList();
          });
        }
      });
    },
    // 取消按钮
    handleCancel() {
      this.dialog.open = false;
      this.handleReset();
    },
    // 表单重置
    handleReset() {
      this.formdata = {};
      this.resetForm("form");
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('monitor/job/exportData', {
        ...this.queryParams
      }, `定时任务导出_${moment().format('YYYY-MM-DD')}.xlsx`, 'application/json;charset=utf-8')
    }
  }
};
</script>

<style lang="scss" scoped>

</style>
